<template>
	<div class="ll-page">
		<div style="padding: 10px">
			<n-button type="success" @click="handleExport">导出数据</n-button>
			<n-button style="margin-left: 6px" @click="backPage">返回banner管理</n-button>
		</div>
		<!-- S 查询 -->
		<div class="ll-page-query flex">
			<n-form
				inline
				:model="searchForm"
				label-placement="left"
				:show-feedback="false"
				class="flex-1 flex-wrap"
			>
				<n-form-item label="事业群：" path="causeId">
					<n-select
						v-model:value="searchForm.configId"
						:options="configOptions"
						placeholder="请选择"
						filterable
						class="w-193px"
						@update:value="causeIdChange"
					/>
				</n-form-item>
				<n-form-item label="站点：" path="locationId">
					<n-select
						v-model:value="searchForm.locationId"
						filterable
						:options="locationOptions"
						placeholder="请选择"
						class="w-193px"
						@update:value="getList"
					/>
				</n-form-item>

				<n-form-item label="展示位置：" path="positionType">
					<n-select
						v-model:value="searchForm.positionType"
						:options="positionTypeOption"
						class="w-193px"
						@update:value="getList"
					/>
				</n-form-item>

				<n-form-item label="投放渠道:" path="channel">
					<n-select
						v-model:value="searchForm.channel"
						:options="channelOption"
						class="w-193px"
						@update:value="getList"
					/>
				</n-form-item>
				<n-form-item>
					<n-button color="rgba(0, 0, 0, 0.1)" text-color="#333333" @click="handelReset">
						重置
					</n-button>
				</n-form-item>
			</n-form>
			<div>
				<n-input
					v-model:value="searchForm.keyWord"
					placeholder="请输入Banner ID/产品ID/产品名称"
					style="width: 320px"
					@keydown.enter="getList"
				>
					<template #suffix>
						<img
							src="@/assets/images/icon_symbol_search@2x.png"
							alt=""
							style="width: 18px; height: 18px"
						/>
					</template>
				</n-input>
			</div>
		</div>

		<!-- E 查询 -->

		<!-- S 表格 -->
		<div class="ll-page-table">
			<n-data-table
				:columns="analysisColumns"
				:data="tableData"
				:loading="tableLoading"
				:pagination="paginationReactive"
				:remote="true"
				flex-height
				:style="{ height: '100%' }"
				:scroll-x="2500"
			/>
		</div>
		<!-- E 表格 -->
		<bannerDetails ref="bannerDetailsRef" @commit="getList"></bannerDetails>
	</div>
</template>

<script setup>
import { h, reactive, ref, nextTick, watch } from 'vue';
import { NButton, NImage, useMessage, useDialog } from 'naive-ui';
import { NTooltip } from 'naive-ui';
import bannerDetails from './components/bannerDetails.vue';

import {
	locationAllList,
	locationconfAll,
	historyBannerList,
	areaHistoryBannerList,
	historyListExport,
	areaHistoryListExport
} from '@/api/bannerMange';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();
const bannerDetailsRef = ref();

const message = useMessage();
const dialog = useDialog();

const analysis = ref(false); //分析模式
// 判断是否包含角色
const hasRoles = ref(false);
const roleIsAdmin = ref(false);

const tableLoading = ref(false);

const searchForm = reactive({
	keyWord: null,
	channel: '',
	configId: '',
	locationId: '',
	positionType: ''
});
const positionTypeOption = [
	{ label: '全部', value: '' },
	{ label: '探店', value: 1 },
	{ label: '素材圈', value: 2 }
];
const channelOption = [
	{ label: '全部', value: '' },
	{ label: '达人营小程序', value: 1 },
	{ label: '达人营App', value: 2 }
];
const configOptions = ref([]); //事业群：
const locationOptions = ref([]); //站点ID

const locationconAll = async () => {
	//事业群
	configOptions.value = [];
	let params = {
		admin: roleIsAdmin.value ? 1 : 0
	};
	let res = await locationconfAll(params);
	if (res && res.code === 200) {
		let list = res.data || [];
		configOptions.value = list.map((item) => {
			item.label = item.name;
			item.value = item.configId;
			return item;
		});
	}
	configOptions.value.unshift({
		label: '全部',
		value: ''
	});
};
const backPage = () => {
	if (roleIsAdmin.value) {
		router.replace({
			path: '/bannerMange/bannerListAdmin'
		});
	} else {
		router.replace({
			path: '/bannerMange/bannerList'
		});
	}
};

const locationList = async (configId = '') => {
	locationOptions.value = [];

	//站点列表
	let params = {
		city: '',
		configId: configId,
		admin: roleIsAdmin.value ? 1 : 0
	};
	let res = await locationAllList(params);
	if (res && res.code === 200) {
		let list = res.data || [];
		locationOptions.value = list.map((item) => {
			item.label = item.city;
			item.value = item.id;
			return item;
		});
	}
	locationOptions.value.unshift({
		label: '全部',
		value: ''
	});
};
const causeIdChange = (val) => {
	searchForm.locationId = '';
	locationList(val);
	getList();
};

const handelReset = () => {
	searchForm.keyWord = null;
	searchForm.channel = '';
	searchForm.configId = '';
	searchForm.locationId = '';
	searchForm.positionType = '';
	getList();
};

const paginationReactive = reactive({
	pageCount: 1,
	page: 1,
	pageSize: 10,
	showSizePicker: true,
	pageSizes: [10, 20, 50],
	itemCount: 0,
	prefix({ itemCount }) {
		return `共${itemCount}条`;
	},
	onChange: (page) => {
		paginationReactive.page = page;
		getList();
	},
	onPageSizeChange: (pageSize) => {
		paginationReactive.pageSize = pageSize;
		paginationReactive.page = 1;
		getList();
	}
});
const renderTooltip = (trigger, content) => {
	return h(NTooltip, null, {
		trigger: () => trigger,
		default: () => content
	});
};
// 导出
const handleExport = () => {
	dialog.success({
		title: '导出excel',
		content: '是否导出',
		positiveText: '确定',
		onPositiveClick: async () => {
			let res;
			if (roleIsAdmin.value) {
				// 是否包含管理员
				res = await historyListExport(searchForm);
			} else {
				res = await areaHistoryListExport(searchForm);
			}

			if (res) return getExcel('历史banner列表.xlsx', res);
		}
	});
};
const getExcel = (name, blobObj) => {
	let elink = document.createElement('a');
	let blob = new Blob([blobObj], { type: 'application/vnd.ms-excel' });
	elink.href = URL.createObjectURL(blob);
	elink.download = name;
	elink.style.display = 'none';
	document.body.appendChild(elink);
	elink.click();
	document.body.removeChild(elink);
	URL.revokeObjectURL(blob);
};
//分析模式
const analysisColumns = [
	{
		title: 'Banner ID',
		width: 100,
		key: 'bannerId'
	},
	{
		title: 'Banner信息',
		key: 'bannerName',
		width: 180,
		render(row) {
			if (row.type == 1) {
				return [
					h('div', {}, `事业群：${row.configName ? row.configName : '暂无'}`),
					h('div', {}, `站点：${row.location ? row.location : '暂无'}`),
					h('div', {}, `产品ID：${row.productId ? row.productId : '暂无'}`),
					h('div', {}, `产品名称：${row.productName ? row.productName : '暂无'}`)
				];
			}
			return row.bannerName;
		}
	},
	{
		title: '图片',
		width: 150,
		key: 'content',
		render(row) {
			return h(NImage, { width: '80', height: '50', src: row.content });
		}
	},
	{
		title: '创建时间',
		key: 'createTime',
		width: '200',
		render(row) {
			return [
				h('div', {}, `创建时间：${row.createTime ? row.createTime : '暂无'}`),
				h('div', {}, `展示时效：${row.startTime}-${row.endTime}`)
			];
		}
	},
	{
		title: '类型',
		width: 120,
		key: 'type',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.type === 1) {
							return '产品';
						} else if (row.type === 2) {
							return '自定义';
						}
					}
				}
			);
		}
	},

	{
		title: '状态',
		width: 100,

		key: 'status',
		render(row) {
			return h(
				'div',
				{
					style: {
						borderRadius: '4px',
						textAlign: 'center',
						background: 'rgba(179, 143, 143, 0.08)',
						lineHeight: '16px',
						fontSize: '12px',
						fontWeight: 600,
						color: 'rgba(208, 48, 80,1)',
						width: '46px'
					}
				},
				`下线`
			);
		}
	},
	{
		title: '投放渠道',
		width: 150,
		key: 'channel',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.channel === 1) {
							return '达人营小程序 ';
						} else if (row.channel === 2) {
							return '达人营App';
						}
					}
				}
			);
		}
	},
	{
		title: '展示位置',
		width: 150,
		key: 'positionType',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.positionType === 1) {
							return '探店 ';
						} else if (row.positionType === 2) {
							return '素材圈';
						}
					}
				}
			);
		}
	},
	{
		title: '链接',
		key: 'linkUrl',
		width: 150,
		render(row) {
			return h(
				'span',
				{
					style: {
						color: '#1D6FE9'
					}
				},
				`${row.linkUrl}`
			);
		}
	},

	{
		title: '曝光量 PV',
		width: 150,
		key: 'exposurePV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '曝光量 PV' }), '有效曝光次数');
		}
	},
	{
		title: '曝光量UV',
		width: 150,
		key: 'exposureUV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '曝光量UV' }), '有效曝光次数 (已去重)');
		}
	},
	{
		title: '人均曝光次数',
		width: 150,
		key: 'exposureAver',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '人均曝光次数' }), '曝光次数/曝光人数');
		}
	},
	{
		title: '点击量PV',
		width: 150,
		key: 'clickPV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击量PV' }), '被点击次数');
		}
	},
	{
		title: '点击量UV',
		width: 150,
		key: 'clickUV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击量UV' }), '被点击次数（已去重）');
		}
	},
	{
		title: '人均点击次数',
		width: 150,
		key: 'clickAver',

		className: 'Tooltip',
		title(column) {
			return renderTooltip(
				h('span', {}, { default: () => '人均点击次数' }),
				'可反应对用户的吸引度'
			);
		}
	},
	//
	{
		title: '点击率',
		width: 150,
		key: 'clickRate',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击率' }), '点击量UV/曝光量UV');
		}
	},
	{
		title: '操作',
		key: 'actions',
		width: 120,
		fixed: 'right',
		render(row, index) {
			return buttonHandle(row, index);
		}
	}
];
const buttonHandle = (row, index) => {
	let actionsButton = [
		h(
			NButton,
			{
				size: 'small',
				text: true,
				type: 'primary',
				style: {
					display: 'block',
					fontSize: '14px',
					marginBottom: '16px'
				},
				onClick: () => handelBannerDetails(row)
			},
			{ default: () => '详情' }
		)
	];
	return actionsButton;
};
const handelBannerDetails = (row) => {
	let params = {
		bannerId: row.bannerId
	};
	bannerDetailsRef.value.init(row.bannerId);
};
let tableData = ref([]);
const getList = async () => {
	tableLoading.value = true;
	const params = {
		...searchForm,
		pageIndex: paginationReactive.page,
		pageSize: paginationReactive.pageSize
	};

	let res;
	if (roleIsAdmin.value) {
		// 是否包含管理员
		res = await historyBannerList(params);
	} else {
		res = await areaHistoryBannerList(params);
	}
	if (res.code === 200) {
		tableData.value = res.data.productList;
		paginationReactive.itemCount = res.data.total;
	} else {
		tableData.value = [];
		paginationReactive.itemCount = 0;
	}
	tableLoading.value = false;
};
const init = () => {
	hasRoles.value =
		router.currentRoute.value.meta?.roles && router.currentRoute.value.meta?.roles.length > 0; //路由角色
	if (hasRoles.value) {
		let roles = router.currentRoute.value.meta.roles;
		roleIsAdmin.value = roles.includes('Admin');
	} else {
		roleIsAdmin.value = false;
	}
	locationconAll();
	locationList();
	getList();
};
nextTick(() => {
	init();
});

// 监听路由变化
watch(
	() => route.path,
	() => {
		handelReset();
		init();
	}
);
</script>

<style lang="less" scoped>
.ll-page {
	height: 100%;
	flex-direction: column;
	display: flex;
	background-color: #ffffff;
	&-query {
		background: @bg;
		padding: @padding-10;
		margin-right: 10px;
		margin-left: 10px;
		margin-top: 10px;
		border-radius: 3px;
		border: 1px solid #f0f0f0;
	}
	.type {
		padding: 10px;
		display: flex;
		&-box {
			display: flex;
			&-item {
				cursor: pointer;
				width: 80px;
				line-height: 36px;
				text-align: center;
				background: #f2f3f5;
				border: 1px solid #e5e5e5;
				font-size: 14px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #4e5969;

				&.isActive {
					background: #ffffff;
					box-shadow: inset 0px -1px 0px 0px #ffffff;
					border-bottom: 1px solid transparent;
				}
				&:nth-child(2) {
					border-left: none;
					border-right: none;
				}
			}
			&-hr {
				border-bottom: 1px solid #e5e5e5;
			}
		}
	}
	.mode-box {
		padding: 10px;
		display: flex;
		&-item {
			display: flex;
			align-items: center;
			margin-right: 20px;
			span {
				font-size: 14px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
				padding-right: 8px;
			}
		}
	}

	&-table {
		padding: 10px;
		overflow: hidden;
		flex: 1 1 0%;
	}
}
</style>
